package com.example.forum.interceptor;

import com.example.forum.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Configuration
public class HandlerInterceptor implements org.springframework.web.servlet.HandlerInterceptor {


    @Value("${bit-forum.login.url}")
    private String defaultUrl;
    /**
     * 强制登录
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        if(!defaultUrl.startsWith("/")) {
//            defaultUrl = "/" + defaultUrl;
//        }
        String jwt = request.getHeader("user_token");
        System.out.println("jwt:" + jwt);
        if(jwt == null || !StringUtils.hasLength(jwt) || jwt.equals("")) {
            log.error("令牌为空");
//            response.sendRedirect(defaultUrl);
            response.setStatus(401);//未认证状态
            return false;
        }
        Claims claims = JWTUtils.parseJwt(jwt);
        if(claims == null) {
            //强制登录
            log.error("令牌校验失败");
            response.setStatus(401);//未认证状态
//            response.sendRedirect(defaultUrl);
            return false;
        }
        return true;
    }
}
